# -*- coding: utf-8 -*-

import requests, BaseFunction as bf, MyClass as mc
import lxml
from lxml import etree

head = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
url = 'http://www.xbiquge.la/modules/article/waps.php'


def post(url, param):
    try:
        r = requests.post(url, headers=head, data=param)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return '地址异常'


def getText(url):
    try:
        r = requests.get(url, headers=head)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return '地址异常'


# 参数 章节集合   返回：带正文的章节集合
def GetBody(zjc):
    i = 1
    a = len(zjc)
    for zj in zjc:
        htmlbody = etree.HTML(getText(zj.href))
        zj.MainBody = ''.join(htmlbody.xpath('//*[@id="content"]/text()')).strip().replace('\n', '<br>').replace('\r',
                                                                                                                 '<br>')
        print(str(i) + '/' + str(a))
        i += 1
    return zjc

def getMainBody(aimlink):
    htmlbody = etree.HTML(getText(aimlink))
    MainBody = ''.join(htmlbody.xpath('//*[@id="content"]/text()')).strip()
    return MainBody

# 获取章节列表
def GetChapterList(bookherf):
    html = etree.HTML(getText(bookherf))
    html1 = html.xpath('//*[@id="list"]/dl/dd')
    zjc = []
    num = 1
    for i in html1:
        name = ''.join(i.xpath('.//a/text()')).strip()
        href = 'http://www.xbiquge.la' + ''.join(i.xpath('.//a/@href')).strip()
        zjc.append(mc.Section(num, name, href, 'temp'))
        num += 1
    return zjc


# 获取搜索结果
def GetSearchResult(name):
    param = {'searchkey': name}
    text = post(url, param)
    html = etree.HTML(text)
    html2 = html.xpath('//*[@id="checkform"]/table/tr')
    bookList = []
    for j in html2:
        name = j.xpath('//*[@class="even"]/a/text()')
        bookherf = j.xpath('//*[@class="even"]/a/@href')
        author = j.xpath('//*[@class="even"]/text()')
        utime = j.xpath('//*[@class="odd"][2]/text()')
        for i in range(0, len(name)):
            book = mc.book('', name[i], author[i], bookherf[i], '新笔趣阁', utime[i])
            bookList.append(book)
    return bookList
